package com.woniu.springsecurity.config;

import com.woniu.springsecurity.exception.CustomAccessDeniedExceptionHandler;
import com.woniu.springsecurity.exception.CustomAuthenticationEntryPoint;
import com.woniu.springsecurity.service.CustomUserDetailService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;

import javax.annotation.Resource;

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)//开启方法级别权限控制注解
public class CustomSpringSecurityConfig extends WebSecurityConfigurerAdapter {
    @Resource
    private UserDetailsService userDetailService;

    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
//        auth.userDetailsService(userDetailService).passwordEncoder(NoOpPasswordEncoder.getInstance());//自定义用户详情服务
        auth.userDetailsService(userDetailService).passwordEncoder(bCryptPasswordEncoder());//加密，自定义用户详情服务
//        auth.inMemoryAuthentication()
//                .withUser("dll")
//                .password("{noop}123") //{noop}表示不加密
//                .roles("student")
//                .and()
//                .withUser("lqz")
//                .password("{noop}123")
//                .roles("teacher", "admin");
    }

    // 配置拦截规则, 拦截规则的配置需要继承WebSecurityConfigurerAdapter
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
//                .antMatchers("/admin/**").hasRole("admin")
//                .antMatchers("/teacher/**").hasRole("teacher")
                .antMatchers("/test/info").permitAll()//需要认证
                .anyRequest().authenticated()//除上述规则的其它请求都需要认证
                .and()
                .exceptionHandling()
                .accessDeniedHandler(new CustomAccessDeniedExceptionHandler())//权限不足处理
//                .authenticationEntryPoint(new CustomAuthenticationEntryPoint())//认证失败处理
                .and()
                .formLogin(); //开启表单登录
    }


}
